using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using Microsoft.BizTalk.Bam.EventObservation;
using System.Xml;
using System.Reflection;
using System.Xml.XPath;
using GenerateTypedBamApi;
using System.Diagnostics;
using Microsoft.XLANGs.BaseTypes;

namespace BTS_Utilities
{
    public class BAMWriter
    {
        
        //const string PrimaryImportConnectionString = "Server=.;Database=BAMPrimaryImport;Trusted_Connection=yes;";
        #region 270 Request
        /// <summary>
        /// This writes the BAM information for 270's in a loop.  So it iterates over the entire document writing out the BAM entries
        /// </summary>
        /// <param name="Document"></param>
        public static void Write_270_Request_BAM(XmlDocument Document)
        {
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request node
            string xpathInfo = "/ns0:Root/EB_270";
            XmlNodeList nodes = Document.SelectNodes(xpathInfo,_mgr);
            DirectESApi.EB_270 _request;

            for (int i = 0; i < nodes.Count; i++)
            {
                //Console.WriteLine("/t/tWriting 270 Request Activity");
                int currentNode = i + 1;
                string currentRoot = xpathInfo + "[" + currentNode + "]";

                //Build Unique Identifier
                //string _TransactionID = Document.SelectSingleNode("/ns0:Root/EB_270[" + currentNode + "]/SubmitterTransactionIdentifier", _mgr).InnerText.ToString();
                //string _InfoSourceID = Document.SelectSingleNode("/ns0:Root/EB_270[" + currentNode + "]/SourcePrimaryIdentifier", _mgr).InnerText.ToString();
                //string _SubscriberID = Document.SelectSingleNode("/ns0:Root/EB_270[" + currentNode + "]/SubscriberPrimaryIdentifier", _mgr).InnerText.ToString();
                //string _uniqueID = _TransactionID + "_" + _InfoSourceID + "_" + _SubscriberID;

                _request = new DirectESApi.EB_270(Guid.NewGuid().ToString());
                
                _request.BeginEB_270Activity();

                string path = "";

                //Loop over the nodes and set the corresponding type names

                
                XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
                ReflectTypeAndSetValue(_nodes, _request);

                string xpathToChildren = currentRoot + "/EB_270_Details";
                XmlNodeList childNodes = Document.SelectNodes(xpathToChildren, _mgr);

                //Add Related Activities.  This relates the child line items back to the original request.

                for (int childCounter = 0; childCounter < childNodes.Count; childCounter++)
                {
                    //XPATH is 1 based arrays while .NET is zero.  Create a new int to correct
                    int newInt = childCounter + 1;
                    string childXPATH = currentRoot + "/EB_270_Details[" + newInt + "]";
                    string childActivityID = Write_270_RequestDetails_BAM(Document, childXPATH, _request);
                    DirectEventStream _de = new DirectEventStream();

                    try
                    {
                        _de.ConnectionString = ConfigurationManager.ConnectionStrings["BAMPrimaryImport"].ConnectionString;
                    }
                    catch(Exception e)
                    {
                        throw new Exception("BTSUtilities::BAMWriter - Invalid BAMPrimaryImport Connection Setting or connection seting not found in BTSNTSvc.exe.config", e);
                        //_de.ConnectionString = PrimaryImportConnectionString;
                    }

                    _de.AddRelatedActivity("EB_270", _request.ActivityID, "EB_270_Details", childActivityID);
                    
                }
                _request.CommitEB_270Activity();
                _request.EndEB_270Activity();
            }

        }
        /// <summary>
        /// Line items detals for 270
        /// </summary>
        /// <param name="Document"></param>
        /// <param name="xPathToChild"></param>
        /// <param name="parentObject"></param>
        /// <returns></returns>
        internal static string Write_270_RequestDetails_BAM(XmlDocument Document, string xPathToChild, DirectESApi.EB_270 parentObject)
        {
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request Details node
            DirectESApi.EB_270_Details _request;

            string currentRoot = xPathToChild;
            
            _request = new DirectESApi.EB_270_Details(System.Guid.NewGuid().ToString());
            _request.BeginEB_270_DetailsActivity();

            string path = "";
            //Loop over the nodes and set the corresponding type names

            Type _requestType = _request.GetType();

            XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
            ReflectTypeAndSetValue(_nodes, _request);


            _request.CommitEB_270_DetailsActivity();

            DirectEventStream _de = new DirectEventStream();
            try
            {
                _de.ConnectionString = ConfigurationManager.ConnectionStrings["BAMPrimaryImport"].ConnectionString;
            }
            catch(Exception e)
            {
                throw new Exception("BTSUtilities::BAMWriter - Invalid BAMPrimaryImport Connection Setting or connection seting not found in BTSNTSvc.exe.config", e);
                //_de.ConnectionString = PrimaryImportConnectionString;
            }
            _de.AddRelatedActivity("EB_270_Details", _request.ActivityID, "EB_270", parentObject.ActivityID);

            _request.CommitEB_270_DetailsActivity();
            _request.EndEB_270_DetailsActivity();
            return _request.ActivityID;

        }
        #endregion

        #region 271 Response
        /// <summary>
        /// Writes 271 information in a loop.
        /// </summary>
        /// <param name="Document"></param>
        public static void Write_271_Response_BAM(XmlDocument Document)
        {
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request node
            string xpathInfo = "/ns0:Root/EB_271";
            XmlNodeList nodes = Document.SelectNodes(xpathInfo,_mgr);
            OrchestrationESApi.EB_271 _request;

            for (int i = 0; i < nodes.Count; i++)
            {
                int currentNode = i + 1;
                string currentRoot = xpathInfo + "[" + currentNode + "]";

                //string _TransactionID = Document.SelectSingleNode("/ns0:Root/EB_271[" + currentNode + "]/SubmitterTransactionIdentifier", _mgr).InnerText.ToString();
                //string _InfoSourceID = Document.SelectSingleNode("/ns0:Root/EB_271[" + currentNode + "]/SourcePrimaryIdentifier", _mgr).InnerText.ToString();
                //string _SubscriberID = Document.SelectSingleNode("/ns0:Root/EB_271[" + currentNode + "]/SubscriberPrimaryIdentifier", _mgr).InnerText.ToString();
                //string _uniqueID = _TransactionID + "_" + _InfoSourceID + "_" + _SubscriberID;

                _request = new OrchestrationESApi.EB_271(Guid.NewGuid().ToString());

                _request.BeginEB_271Activity();

                string path = "";

                //Loop over the nodes and set the corresponding type names

                Type _requestType = _request.GetType();

                XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
                ReflectTypeAndSetValue(_nodes, _request);

                string xpathToChildren = currentRoot + "/EB_271_Details";
                XmlNodeList childNodes = Document.SelectNodes(xpathToChildren, _mgr);

                //Add Related Activities
                //DirectEventStream.AddRelatedActivity("EB_270", _uniqueID, "EB_271", _uniqueID);
                //DirectEventStream.AddRelatedActivity("EB_271", _uniqueID, "EB_270", _uniqueID);

                for (int childCounter = 0; childCounter < childNodes.Count; childCounter++)
                {
                    //XPATH is 1 based arrays while .NET is zero.  Create a new int to correct
                    int newInt = childCounter + 1;
                    string childXPATH = currentRoot + "/EB_271_Details[" + newInt + "]";
                    string childActivityID = Write_271_ResponseDetails_BAM(Document, childXPATH, _request);
                    //New Orchestration way of adding references
                    _request.AddReferenceToAnotherActivity("EB_271_Details", childActivityID);
                    //Old DirectASPI
                    //DirectEventStream _de = new DirectEventStream();
                    //try
                    //{
                    //  _de.ConnectionString = ConfigurationManager.ConnectionStrings["BAMPrimaryImport"].ConnectionString;
                    //}
                    //catch(Exception e)
                    //{
                    //  throw new Exception("BTSUtilities::BAMWriter - Invalid BAMPrimaryImport Connection Setting or connection seting not found in BTSNTSvc.exe.config", e);
                    //  //_de.ConnectionString = PrimaryImportConnectionString;
                    //}
                    //_de.AddRelatedActivity("EB_271", _request.ActivityID, "EB_271_Details", childActivityID);
                }
                _request.CommitEB_271Activity();
                _request.EndEB_271Activity();
            }

        }
        /// <summary>
        /// Internal method for line item details
        /// </summary>
        /// <param name="Document"></param>
        /// <param name="xPathToChild"></param>
        /// <param name="parentObject"></param>
        /// <returns></returns>
        internal static string Write_271_ResponseDetails_BAM(XmlDocument Document, string xPathToChild, OrchestrationESApi.EB_271 parentObject)
        {
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request Details node
            OrchestrationESApi.EB_271_Details _request;


            string currentRoot = xPathToChild;
            _request = new OrchestrationESApi.EB_271_Details(System.Guid.NewGuid().ToString());
            _request.BeginEB_271_DetailsActivity();

            string path = "";
            //Loop over the nodes and set the corresponding type names

            Type _requestType = _request.GetType();

            XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
            ReflectTypeAndSetValue(_nodes, _request);
            _request.CommitEB_271_DetailsActivity();

            _request.AddReferenceToAnotherActivity("EB_271", parentObject.ActivityID);

            //OrchestrationEventStream _de = new OrchestrationEventStream();
            //try
            //{
            //  _de.ConnectionString = ConfigurationManager.ConnectionStrings["BAMPrimaryImport"].ConnectionString;
            //}
            //catch
            //{
            //  throw new Exception("BTSUtilities::BAMWriter - Invalid BAMPrimaryImport Connection Setting or connection seting not found in BTSNTSvc.exe.config", e);
            //  //_de.ConnectionString = PrimaryImportConnectionString;
            //}
            //_de.AddRelatedActivity("EB_271_Details", _request.ActivityID, "EB_271", parentObject.ActivityID);

            _request.EndEB_271_DetailsActivity();
            return _request.ActivityID;

        }
        #endregion

        internal static void ReflectTypeAndSetValue(XmlNodeList nodes, object ObjectToSet)
        {
            Type _objType = ObjectToSet.GetType();

            foreach (XmlNode _nodeInfo in nodes)
            {
                foreach (XmlNode _childNode in _nodeInfo.ChildNodes)
                {
                    PropertyInfo _prop = _objType.GetProperty(_childNode.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
                    if (_prop != null && _childNode.InnerText.Length !=0)
                    {
                        //We need to convert the x12 date to the .NET FX Datetime.
                        //Example is 070314 which is 0/14/2007 in .net
                        object _newValue;
                        if (_prop.PropertyType.UnderlyingSystemType == typeof(System.DateTime))
                        {
                            string newDateString = convertDT(_childNode.InnerText);
                            _newValue = System.Convert.ChangeType(newDateString, _prop.PropertyType.UnderlyingSystemType);
                        }
                        else
                        {
                            _newValue = System.Convert.ChangeType(_childNode.InnerText, _prop.PropertyType.UnderlyingSystemType);
                        }
                        _prop.SetValue(ObjectToSet, _newValue, null);
                    }
                }
            }
        }
        internal static string convertDT(string DTInbound)
        {
            //Comes in 070314
            string year = "";
            string month ="";
            string day = "";
            if (DTInbound.Length == 6)
            {
                year = DTInbound.Substring(0, 2);
                month = DTInbound.Substring(2, 2);
                day = DTInbound.Substring(4, 2);
            }
            else
            {
                return DTInbound;
            }
            if (System.Convert.ToInt16(year) > 27)
            {
                year = "19" + year;
            }
            else
            {
                year = "20" + year;
            }
            return month + @"/" + day + @"/" + year;
        }

        #region 837I Request
        /// <summary>
        /// This writes the BAM information for 837's in a loop.  So it iterates over the entire document writing out the BAM entries
        /// </summary>
        /// <param name="Document"></param>
        public static void Write_837I_Request_BAM(string EnvelopeActivityID, XmlDocument Document)
        {
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request node
            string xpathInfo = "/ns0:Root/CLM_837I";
            XmlNodeList nodes = Document.SelectNodes(xpathInfo, _mgr);
            OrchestrationESApi.CLM_837I _request;

            for (int i = 0; i < nodes.Count; i++)
            {
                //Console.WriteLine("/t/tWriting 837 Request Activity");
                int currentNode = i + 1;
                string currentRoot = xpathInfo + "[" + currentNode + "]";

                //New GUID Activity ID 
                _request = new OrchestrationESApi.CLM_837I(Guid.NewGuid().ToString());

                //Console.WriteLine("/t/tXML:" + Document.SelectSingleNode(currentRoot).InnerXml.ToString());
                _request.BeginCLM_837IActivity();

                //Loop over the nodes and set the corresponding type names
                XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
                ReflectTypeAndSetValue(_nodes, _request);

                _request.AddReferenceToAnotherActivity("EDI_Envelope_Interchange", EnvelopeActivityID);

                _request.CommitCLM_837IActivity();
                //End the Request
                _request.EndCLM_837IActivity();
            }

        }
        #endregion
        #region 835 Response
        /// <summary>
        /// This writes the BAM information for 837's in a loop.  So it iterates over the entire document writing out the BAM entries
        /// </summary>
        /// <param name="Document"></param>
        public static void Write_835_Response_BAM(string EnvelopeActivityID, XmlDocument Document)
        {
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request node
            string xpathInfo = "/ns0:Root/CLM_835";
            XmlNodeList nodes = Document.SelectNodes(xpathInfo, _mgr);
            OrchestrationESApi.CLM_835 _request;

            for (int i = 0; i < nodes.Count; i++)
            {
                //Console.WriteLine("/t/tWriting 835 Request Activity");
                int currentNode = i + 1;
                string currentRoot = xpathInfo + "[" + currentNode + "]";


                _request = new OrchestrationESApi.CLM_835(Guid.NewGuid().ToString());
             
                //Console.WriteLine("/t/tXML:" + Document.SelectSingleNode(currentRoot).InnerXml.ToString());
                _request.BeginCLM_835Activity();

                //Loop over the nodes and set the corresponding type names
                XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
                ReflectTypeAndSetValue(_nodes, _request);
                
                _request.AddReferenceToAnotherActivity("EDI_Envelope_Interchange", EnvelopeActivityID);

                _request.CommitCLM_835Activity();
                //End the Request
                _request.EndCLM_835Activity();

                //BUG::BUG - Research settign relationships after an earlier completed activity has been set.
                //DirectEventStream.AddRelatedActivity("CLM_837I", _uniqueID, "CLM_835", _uniqueID);
                //DirectEventStream.AddRelatedActivity("CLM_835", _uniqueID, "CLM_837I", _uniqueID);
            }

        }
        #endregion

        #region Availity HTTP Request
        /// <summary>
        /// This writes the BAM information for 837's in a loop.  So it iterates over the entire document writing out the BAM entries
        /// </summary>
        /// <param name="Document"></param>
        public static string Write_Availity_Realtime_Messaging_Request_BAM(XmlDocument Document)
        {
            string ActivityID = "";
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request node
            string xpathInfo = "/ns0:Root/Availity_Realtime_Messaging";
            XmlNodeList nodes = Document.SelectNodes(xpathInfo, _mgr);
            OrchestrationESApi.Availity_Realtime_Messaging _request;

            //The Availity HTTP request can only handle a single record at a time.  We should never have to loop.
            for (int i = 0; i < nodes.Count; i++)
            {
                //Console.WriteLine("/t/tWriting 837 Request Activity");
                int currentNode = i + 1;
                string currentRoot = xpathInfo + "[" + currentNode + "]";

                ActivityID = Guid.NewGuid().ToString();
                
                //New GUID Activity ID 
                _request = new OrchestrationESApi.Availity_Realtime_Messaging(ActivityID);

                //Console.WriteLine("/t/tXML:" + Document.SelectSingleNode(currentRoot).InnerXml.ToString());
                _request.BeginAvaility_Realtime_MessagingActivity();

                //Loop over the nodes and set the corresponding type names
                XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
                ReflectTypeAndSetValue(_nodes, _request);

                //Commit Changes
                _request.CommitAvaility_Realtime_MessagingActivity();
                return ActivityID;
            }
            return null;

        }
        public static void Write_Availity_Realtime_Messaging_Response_BAM(XmlDocument Document, string ActivityID)
        {
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request node
            string xpathInfo = "/ns0:Root/Availity_Realtime_Messaging";
            XmlNodeList nodes = Document.SelectNodes(xpathInfo, _mgr);
            OrchestrationESApi.Availity_Realtime_Messaging _request;

            for (int i = 0; i < nodes.Count; i++)
            {
                //Console.WriteLine("/t/tWriting 837 Request Activity");
                int currentNode = i + 1;
                string currentRoot = xpathInfo + "[" + currentNode + "]";

                //Continue with the ActivityID Provided
                _request = new OrchestrationESApi.Availity_Realtime_Messaging(ActivityID);

                //Loop over the nodes and set the corresponding type names
                XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
                ReflectTypeAndSetValue(_nodes, _request);

                _request.CommitAvaility_Realtime_MessagingActivity();
                //End the BAM activity
                _request.EndAvaility_Realtime_MessagingActivity();
            }

        }
        #endregion
        #region Availity HTTP Request Payer Error
        /// <summary>
        /// This writes the BAM information for 837's in a loop.  So it iterates over the entire document writing out the BAM entries
        /// The Payer can generate one or more errors so this writes them out to the BAM Tables
        /// </summary>
        /// <param name="Document"></param>
        public static void Write_Availity_Realtime_Messaging_PayerError_Response_BAM(XmlDocument Document)
        {
            string ActivityID = "";
            XmlNamespaceManager _mgr = new XmlNamespaceManager(Document.NameTable);
            _mgr.AddNamespace("ns0", "http://HealthcareClaimSchemas.BAM.BAM_Activity_Schema");

            //Iterate over the Auth Request node
            string xpathInfo = "/ns0:Root/Availity_Realtime_Messaging_PayerErrors";
            XmlNodeList nodes = Document.SelectNodes(xpathInfo, _mgr);
            OrchestrationESApi.Availity_Realtime_Messaging_PayerErrors _request;

            //Loop through the errors and write them out to the BAM Tables
            for (int i = 0; i < nodes.Count; i++)
            {
                //Console.WriteLine("/t/tWriting 837 Request Activity");
                int currentNode = i + 1;
                string currentRoot = xpathInfo + "[" + currentNode + "]";

                ActivityID = Guid.NewGuid().ToString();

                //New GUID Activity ID 
                _request = new OrchestrationESApi.Availity_Realtime_Messaging_PayerErrors(ActivityID);

                //Console.WriteLine("/t/tXML:" + Document.SelectSingleNode(currentRoot).InnerXml.ToString());
                _request.BeginAvaility_Realtime_Messaging_PayerErrorsActivity();

                //Loop over the nodes and set the corresponding type names
                XmlNodeList _nodes = Document.SelectNodes(currentRoot, _mgr);
                ReflectTypeAndSetValue(_nodes, _request);

                //Commit Changes
                _request.EndAvaility_Realtime_Messaging_PayerErrorsActivity();
                _request.CommitAvaility_Realtime_Messaging_PayerErrorsActivity();
            }
        }
        #endregion

        #region Claim Messaging Statistics
        public static void Write_ClaimMessagingStatistic_BAM(string EnvelopeActivityID,string MessageDestination, string MessageSource, string MessageDirection, string MessageType, DateTime MessageStartTime, DateTime MessageEndTime, string OrchestrationName, int NumberOfChildMessages, string BTSMessageID, string BTSInterchangeID, string MessageCommunicationMethod, string TransmissionStatus)
        {
            GenerateTypedBamApi.OrchestrationESApi.ClaimMessagingStatistics _request;

            //New GUID Activity ID 
            _request = new OrchestrationESApi.ClaimMessagingStatistics(Guid.NewGuid().ToString());

            _request.BeginClaimMessagingStatisticsActivity();

            _request.MessageDestination = MessageDestination;
            _request.MessageDirection = MessageDirection;
            _request.MessageSource = MessageSource;
            _request.MessageType = MessageType;
            _request.MessageStartTime = MessageStartTime;
            _request.MessageEndTime = MessageEndTime;
            _request.NumberOfChildMessages = NumberOfChildMessages;
            _request.OrchestrationName = OrchestrationName;
            _request.BTSMessageID = BTSMessageID;
            _request.BTSInterchangeID = BTSInterchangeID;
            _request.MessageCommunicationMethod = MessageCommunicationMethod;
            _request.MessageTransmissionSuccessful = TransmissionStatus;

            _request.AddReferenceToAnotherActivity("EDI_Envelope_Interchange", EnvelopeActivityID);

            _request.CommitClaimMessagingStatisticsActivity();
            //End the Request
            _request.EndClaimMessagingStatisticsActivity();
        }
        #endregion
        #region EDI Envelope
        /// <summary>
        /// This writes the EDI Header information for the document in a BAM Table
        /// </summary>
        /// <param name="Document"></param>
        /// 
        public static string Write_EDI_Envelope(XLANGMessage BaseMessage, string BTSMessageID, string BTSInterchangeID, HeadersISA ISAHeader, HeadersGS GSHeader, string ST01, string ST02)
        {
            DirectESApi.EDI_Envelope_Interchange _Interchange;
            DirectESApi.EDI_Envelope_Group _Group;
            DirectESApi.EDI_Envelope_Transaction _Transaction;


            _Interchange = Write_EDI_Envelope_Interchange_BAM(BTSMessageID, BTSInterchangeID, ISAHeader);
            _Group = Write_EDI_Envelope_Group_BAM(BTSMessageID, BTSInterchangeID, GSHeader);
            _Transaction = Write_EDI_TransactionSet_BAM(BTSMessageID, BTSInterchangeID, ST01, ST02);
            //Parent DirectEventStream.AddRelatedActivity("EB_270", _request.ActivityID, "EB_270_Details", childActivityID);
            //Child DirectEventStream.AddRelatedActivity("EB_270_Details", _request.ActivityID, "EB_270", parentObject.ActivityID);
            DirectEventStream _de = new DirectEventStream();
            try
            {
              _de.ConnectionString = ConfigurationManager.ConnectionStrings["BAMPrimaryImport"].ConnectionString;
            }
            catch(Exception e)
            {
                throw new Exception("BTSUtilities::BAMWriter - Invalid BAMPrimaryImport Connection Setting or connection seting not found in BTSNTSvc.exe.config", e);
                //_de.ConnectionString = PrimaryImportConnectionString;
            }

            _de.AddRelatedActivity("EDI_Envelope_Interchange", _Interchange.ActivityID, "EDI_Envelope_Group", _Group.ActivityID);
            _de.AddRelatedActivity("EDI_Envelope_Interchange", _Interchange.ActivityID, "EDI_Envelope_Transaction", _Transaction.ActivityID);

            //Store off the entire payload
            XmlDocument _innerData = (XmlDocument)BaseMessage[0].RetrieveAs(typeof(XmlDocument));
            _de.AddReference("EDI_Envelope_Interchange", _Interchange.ActivityID, "MsgBody", "MessageBody", System.DateTime.Now.ToString(), _innerData.OuterXml.ToString());

            _de.AddRelatedActivity("EDI_Envelope_Group", _Group.ActivityID, "EDI_Envelope_Interchange", _Interchange.ActivityID);
            _de.AddRelatedActivity("EDI_Envelope_Group", _Group.ActivityID, "EDI_Envelope_Transaction", _Transaction.ActivityID);

            _de.AddRelatedActivity("EDI_Envelope_Transaction", _Group.ActivityID, "EDI_Envelope_Group", _Group.ActivityID);
            _de.AddRelatedActivity("EDI_Envelope_Transaction", _Group.ActivityID, "EDI_Envelope_Interchange", _Interchange.ActivityID);


            _Transaction.CommitEDI_Envelope_TransactionActivity();
            _Transaction.EndEDI_Envelope_TransactionActivity();
            _Group.CommitEDI_Envelope_GroupActivity();
            _Group.EndEDI_Envelope_GroupActivity();

            _Interchange.CommitEDI_Envelope_InterchangeActivity();
            _Interchange.EndEDI_Envelope_InterchangeActivity();

            return _Interchange.ActivityID;

        }
        private static DirectESApi.EDI_Envelope_Interchange Write_EDI_Envelope_Interchange_BAM(string BTSMessageID, string BTSInterchangeID, HeadersISA ISAHeader)
        {
            GenerateTypedBamApi.DirectESApi.EDI_Envelope_Interchange _request;


            //New GUID Activity ID 
            _request = new DirectESApi.EDI_Envelope_Interchange(Guid.NewGuid().ToString());

            _request.BeginEDI_Envelope_InterchangeActivity();
            
            _request.BTSMessageID = BTSMessageID;
            _request.BTSInterchangeID = BTSInterchangeID;

            _request.ISA01_AuthorizationQualifier = ISAHeader.ISA01;
            _request.ISA02_AuthorizationInformation = ISAHeader.ISA02;
            _request.ISA03_SecurityQualifier = ISAHeader.ISA03;
            _request.ISA04_SecurityInformation = ISAHeader.ISA04;
            _request.ISA05_SenderQualifier = ISAHeader.ISA05;
            _request.ISA06_SenderID = ISAHeader.ISA06;
            _request.ISA07_ReceiverQualifier = ISAHeader.ISA07;
            _request.ISA08_ReceiverID = ISAHeader.ISA08;
            _request.ISA09_Date = ISAHeader.ISA09;
            _request.ISA10_Time = ISAHeader.ISA10;
            _request.ISA11_ControlStandardsID = ISAHeader.ISA11;
            _request.ISA12_InterchangeControlVersionNumber = ISAHeader.ISA12;
            _request.ISA13_InterchangeControlNumber = ISAHeader.ISA13;
            _request.ISA14_AcknowledgementRequested = ISAHeader.ISA14;
            _request.ISA15_TestIndicator = ISAHeader.ISA15;
            _request.ISA16_SubelementSeparator = ISAHeader.ISA16;
            _request.SegmentTerminator = ISAHeader.SegmentTerminator;
            _request.DataElementSeparator = ISAHeader.DataElementSeparator;


            return _request;
        }
        private static DirectESApi.EDI_Envelope_Group Write_EDI_Envelope_Group_BAM(string BTSMessageID, string BTSInterchangeID, HeadersGS GSHeader)
        {
            GenerateTypedBamApi.DirectESApi.EDI_Envelope_Group _request;

            //New GUID Activity ID 
            _request = new DirectESApi.EDI_Envelope_Group(Guid.NewGuid().ToString());

            _request.BeginEDI_Envelope_GroupActivity();

            _request.BTSInterchangeID = BTSInterchangeID;
            _request.BTSMessageID = BTSMessageID;

            _request.GS01_FunctionalIDCode = GSHeader.GS01;
            _request.GS02_ApplicationSenderCode = GSHeader.GS02;
            _request.GS03_ApplicationReceiverCode = GSHeader.GS03;
            _request.GS04_Date = GSHeader.GS04;
            _request.GS05_Time = GSHeader.GS05;
            _request.GS06_GroupControlNumber = GSHeader.GS06;
            _request.GS07_ResponsibleAgencyCode = GSHeader.GS07;
            _request.GS08_VersionIDCode = GSHeader.GS08;

            return _request;

        }
        private static DirectESApi.EDI_Envelope_Transaction Write_EDI_TransactionSet_BAM(string BTSMessageID, string BTSInterchangeID, string ST01, string ST02)
        {
            GenerateTypedBamApi.DirectESApi.EDI_Envelope_Transaction _request;

            //New GUID Activity ID 
            _request = new DirectESApi.EDI_Envelope_Transaction(Guid.NewGuid().ToString());

            _request.BeginEDI_Envelope_TransactionActivity();

            _request.BTSInterchangeID = BTSInterchangeID;
            _request.BTSMessageID = BTSMessageID;
            _request.ST01_TransactionSetIDCode = ST01;
            _request.ST02_TransactionSetControlNumber = ST02;

            return _request;
        }
        #endregion
        #region MessageLog
        /// <summary>
        /// This writes Message Log information directly to the BAM Subsystem
        /// </summary>
        /// <param name="Document"></param>
        public static void Write_MessageLog_BAM(string EnvelopeActivityID, string BTSMessageID, string BTSInterchangeID, string CurrentStep, string CurrentStepDetails, string NextStep)
        {
            GenerateTypedBamApi.DirectESApi.MessageLog _request;
            
            //New GUID Activity ID 
            _request = new DirectESApi.MessageLog(Guid.NewGuid().ToString());

            _request.BeginMessageLogActivity();

            _request.BeginMessageLogActivity();
            _request.BTSMessageID = BTSMessageID;
            _request.BTSInterchangeID = BTSInterchangeID;

            _request.CurrentStep = CurrentStep;
            _request.CurrentStepDetails = CurrentStepDetails;
            _request.NextStep = NextStep;

            _request.AddReferenceToAnotherActivity("EDI_Envelope_Interchange", EnvelopeActivityID);
            _request.CommitMessageLogActivity();
            
            //End the Request
            _request.EndMessageLogActivity();
        }
        #endregion
        
        #region DataFile
        /// <summary>
        /// This writes Data File Details to the BAM Tables
        /// </summary>
        /// <param name="Document"></param>
        public static void Write_FileData_BAM(string EnvelopeActivityID, Microsoft.XLANGs.BaseTypes.XLANGMessage Message)
        {
            XmlDocument doc = new XmlDocument();
            StringBuilder _bldr = new StringBuilder();
            _bldr.Append("<Properties>");
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                if (assembly.FullName.Contains("Microsoft.BizTalk.GlobalPropertySchemas") || assembly.FullName.Contains("Microsoft.BizTalk.Edi.BaseArtifacts"))
                {
                        
                        Type[] types = assembly.GetTypes();
                        foreach (Type typeInfo in types)
                        {
                            try
                            {
                                //Grab TS, EDI, File, HTTP and FTP inforamtion
                                //Make sure this type is not a schema but rather a MessageContextProperty
                                if (typeInfo.BaseType.FullName.StartsWith("Microsoft.XLANGs.BaseTypes.MessageContextPropertyBase"))
                                    //&& (typeInfo.FullName.StartsWith("BTS") || typeInfo.FullName.StartsWith("EDI") || typeInfo.FullName.StartsWith("FILE") || typeInfo.FullName.StartsWith("HTTP") || typeInfo.FullName.StartsWith("FTP")))
                                {                                        
                                    if(Message.GetPropertyValue(typeInfo) != null)
                                    {
                                        GenerateTypedBamApi.OrchestrationESApi.MessageContextProperties _ctx = new OrchestrationESApi.MessageContextProperties(System.Guid.NewGuid().ToString());
                                        _ctx.BeginMessageContextPropertiesActivity();
                                        _ctx.BTSMessageID = Message.GetPropertyValue(typeof(BTS.MessageID)).ToString();
                                        _ctx.BTSInterchangeID = Message.GetPropertyValue(typeof(BTS.InterchangeID)).ToString();
                                        _ctx.ContextName = typeInfo.FullName;
                                        _ctx.ContextValue = Message.GetPropertyValue(typeInfo).ToString();
                                        _ctx.AddReferenceToAnotherActivity("EDI_Envelope_Interchange", EnvelopeActivityID);
                                        //_ctx.CommitMessageContextPropertiesActivity();
                                        _ctx.EndMessageContextPropertiesActivity();
                                        
                                    //_bldr.Append("PropertyName:\t" + typeInfo.FullName + "\tPropertyValue:\t" + Message.GetPropertyValue(typeInfo) + "\n";
                                    }
                                }
                            }
                            catch (System.Exception emsg)
                            {
                                Console.Write(emsg.Message);
                                //Do Nothing
                            }

                        }
                    
                    
                }
            }
            _bldr.Append("</>");
            
        }
        #endregion


    }

    
}
